package pagination

import (
	"gorm.io/gorm"
)

type PageInfo struct {
	Page     int `form:"page" json:"page"`
	PageSize int `form:"page_size" json:"page_size"`
}

type PageResult[T any] struct {
	List     []T   `json:"list"`
	Total    int64 `json:"total"`
	Page     int   `json:"page"`
	PageSize int   `json:"page_size"`
}

// Paginate 通用分页函数
func Paginate[T any](db *gorm.DB, pageInfo PageInfo, out *[]T) (*PageResult[T], error) {
	if pageInfo.Page <= 0 {
		pageInfo.Page = 1
	}
	if pageInfo.PageSize <= 0 {
		pageInfo.PageSize = 10
	}

	var total int64
	if err := db.Count(&total).Error; err != nil {
		return nil, err
	}

	offset := (pageInfo.Page - 1) * pageInfo.PageSize
	if err := db.Offset(offset).Limit(pageInfo.PageSize).Find(out).Error; err != nil {
		return nil, err
	}

	return &PageResult[T]{
		List:     *out,
		Total:    total,
		Page:     pageInfo.Page,
		PageSize: pageInfo.PageSize,
	}, nil
}
